package com.anxpp.calculator.nio;

import java.util.Random;
import java.util.Scanner;

public class Client {
    private static String DEFAULT_HOST = "127.0.0.1";
//    private static String DEFAULT_HOST = "0.0.0.0";
    private static int DEFAULT_PORT = 12345;
    private static ClientHandle clientHandle;
    public static void start(){
        start(DEFAULT_HOST,DEFAULT_PORT);
    }
    private static synchronized void start(String ip,int port){
        if(clientHandle!=null)
            clientHandle.stop();
        clientHandle = new ClientHandle(ip,port);
        new Thread(clientHandle,"Client").start();
    }
    //向服务器发送消息
    public static boolean sendMsg(String msg) throws Exception{
        if(msg.equals("q")) {
            System.out.println("---msg is:" + msg);
            return false;
        }
        clientHandle.sendMsg(msg);
        return true;
    }

    /**
     * 注意：一定要先sleep，这样client才会连接上server，然后再行发送计算表达式
     * 否则会报错java.nio.channels.NotYetConnectedException
     */
    public static void main(String[] args) throws Exception {
        Client.start();
        Thread.currentThread().sleep(1000);
//        while(Client.sendMsg(new Scanner(System.in).nextLine()));
        final char operators[] = {'+', '-', '*', '/'};
        final Random random = new Random(System.currentTimeMillis());
        while(true){
            //随机产生算术表达式
            try{
                Thread.currentThread().sleep(random.nextInt(1000));
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            String expression = random.nextInt(10)+""+operators[random.nextInt(4)]+random.nextInt(10);
            System.out.println("-----------------------------");
            System.out.println("客户端发出请求："+expression);
            if(!expression.contains("/0"))
                Client.sendMsg(expression);
        }
    }

}

